﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
//using Microsoft.Office.Interop.Word;
//using EPocalipse.IFilter;
using DocumentFormat.OpenXml.Packaging;

namespace Jb.Search.TextExtractor
{
    public class MsWordDocument : ITextExtractor
    {
        public MsWordDocument(String filePath)
        {
            this.FilePath = filePath;
        }

        /// <summary>
        /// FilePath of the corresponding file to extract text from
        /// </summary>
        public String FilePath { get; set; }

        /// <summary>
        /// Extracts text from a Microsoft Word Document. Paragraphs are separated by a new line character
        /// This is the obsolete implementation with COM interop
        /// </summary>
        /// <returns></returns>
        //public String ExtractText()
        //{
        //    Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
        //    object miss = System.Reflection.Missing.Value;
        //    object path = FilePath;
        //    object readOnly = true;
        //    Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
        //    StringBuilder totaltext = new StringBuilder();
        //    for (int i = 0; i < docs.Paragraphs.Count; i++)
        //    {
        //        totaltext.AppendFormat(" {0} {1}", Environment.NewLine, docs.Paragraphs[i + 1].Range.Text.ToString());
        //    }
        //    Console.WriteLine(totaltext);
        //    docs.Close();
        //    word.Quit();
        //    return totaltext.ToString();
        //}

        
        /// <summary>
        /// Extracts text from word documents
        /// </summary>
        /// <returns></returns>
        public String ExtractText()
        {
            WordprocessingDocument doc = WordprocessingDocument.Open(this.FilePath, false);
            DocumentFormat.OpenXml.Wordprocessing.Body body = doc.MainDocumentPart.Document.Body;

            String text = body.InnerText;
                return text;
            
        }
    }
}
